package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.MemberApplyEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.MemberApply;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverLevelService;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberApplyService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.SmsTempletService;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "memberapply")
public class MemberApplyController {

    @Autowired
    private MemberApplyService memberApplyService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverLevelService driverLevelService;
    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("memberapply")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("memberapply/list");

            mv.addObject("page", memberApplyService.queryAll());

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }
/*	@RequestMapping("list")
	public ModelAndView list() {
		
		Subject subject = SecurityUtils.getSubject();
		if(subject.isPermitted("driver")){
			ModelAndView mv = new ModelAndView();
			
			mv.setViewName("memberapply/list");
			
			return mv;
		}
		else{
			throw new NoPermissionException();
		}
		
	}*/

    @RequestMapping("listData")
    public @ResponseBody
    Page<MemberApply> listData() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("memberapply")) {

            Page<MemberApply> page = memberApplyService.queryAll();
            return page;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "audit/{id}", method = RequestMethod.GET)
    public ModelAndView audit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("memberapply")) {
            ModelAndView mv = new ModelAndView();

            MemberApply local = memberApplyService.findOne(id);

            mv.addObject("memberapply", local);
            mv.addObject("grades", memberService.listAllGrades());

            mv.setViewName("memberapply/audit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<MemberApply> audit(MemberApply memberApply) {

        Result<MemberApply> result = new Result<MemberApply>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberapply")) {

            String phone = memberApply.getPhone();

            Passenger passenger = memberService.findOnePassengerByPhone(phone);

            if (null == passenger) {
                result.setMessage("该申请客户不存在，无法审核");
            }

            if (passenger.getType() == 0 && memberApply.getType() == 1) {
                result.setMessage("个人客户不能申请企业客户，无法审核");
            }

            if (passenger.getType() == 1 && memberApply.getType() == 0) {
                result.setMessage("企业客户不能申请个人客户，无法审核");
            }

            if (passenger.getType() == 0) {
                passenger.setName(memberApply.getName());
                passenger.setEmail(memberApply.getEmail());
                passenger.setGrade_id(memberApply.getGradeId());
                Result<Passenger> result_p = memberService.updatePersonal(passenger);

                if (result_p.isSuccess()) {
                    String detail =
                        "【%s】审核了个人VIP申请【" + memberApply.getName() + "(" + memberApply.getPhone()
                            + ")】，备注：" + memberApply.getMemo() + "";

                    memberApplyService.delete(memberApply);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    MemberApplyEvent memberApplyEvent = new MemberApplyEvent(passenger);
                    applicationEventMulticaster.multicastEvent(memberApplyEvent);

                    result.setSuccess(true);
                } else {
                    result.setMessage(result_p.getMessage());
                }
            } else if (passenger.getType() == 1) {
                Enterprise enterprise = memberService
                    .findOneEnterprise(passenger.getEnterprise_id());
                enterprise.setName(memberApply.getAgencyName());
                enterprise.setGrade_id(memberApply.getGradeId());
                Result<Enterprise> result_e = memberService.updateEnterprise(enterprise);

                if (result_e.isSuccess()) {
                    String detail =
                        "【%s】审核了企业VIP申请【" + memberApply.getName() + "(" + memberApply.getPhone()
                            + ")】，备注：" + memberApply.getMemo() + "";

                    memberApplyService.delete(memberApply);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    MemberApplyEvent memberApplyEvent = new MemberApplyEvent(passenger);
                    applicationEventMulticaster.multicastEvent(memberApplyEvent);

                    result.setSuccess(true);
                } else {
                    result.setMessage(result_e.getMessage());
                }
            }

            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("memberapply")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                MemberApply memberApply = memberApplyService.findOne(id);
                if (null != memberApply) {

                    String detail =
                        "【%s】删除了VIP申请【" + memberApply.getName() + "(" + memberApply.getPhone()
                            + ")】，备注：" + memberApply.getMemo() + "";

                    memberApplyService.delete(memberApply);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setSuccess(false);
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setSuccess(false);
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }


    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

